package com.rt.cms.service.system;

import com.rt.cms.common.base.Page;
import com.rt.cms.common.base.PageResultSet;
import com.rt.cms.common.base.ResultCodeEnum;
import com.rt.cms.dao.system.UserDao;
import com.rt.cms.data.entity.system.*;
import com.rt.cms.data.dto.system.UserDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private RoleService roleService;

    @Autowired
    private OrganizationService organizationService;

    @Autowired
    private PasswordHelper passwordHelper;

    @Override
    public List<User> selectByExample(UserExample example) {
        return userDao.selectByExample(example);
    }

    @Override
    public PageResultSet<UserDto> findByPage(Page page) {
        UserExample example = new UserExample();
        example.setOffset(page.getOffset());
        example.setLimit(page.getLimit());
        example.setOrderByClause("create_date");
        if (!StringUtils.isEmpty(page.getSearch())) {
            example.or().andUsernameLike("%" + page.getSearch() + "%");
        }
        long count = userDao.countByExample(example);
        List<UserDto> dtoList = new ArrayList<>();
        PageResultSet<UserDto> resultSet = new PageResultSet<>();
        List<Role> roleList = roleService.findAll();

        List<User> userList = userDao.selectByExample(example);
        List<User> userAllList = userDao.selectByExample(null);
        //List<Organization> organizationList = organizationService.findAll();
        for (User user : userList) {
            UserDto dto = new UserDto(user);
            dto.setOrganizationName(user.getOrganizationName());

            if (user.getpId() == null) {
                dto.setpName(null);
                dtoList.add(dto);
                continue;
            }

            for (User buser : userAllList) {
                if (user.getpId() == buser.getId()) {
                    dto.setpName(buser.getOrganizationName() + "<" + buser.getReallyName() + ">");
                    break;
                }
            }

            dtoList.add(dto);
        }
        resultSet.setRows(dtoList);
        resultSet.setTotal(count);
        return resultSet;
    }

    private String getRoleNames(Collection<Long> roleIds, List<Role> roleList) {
        if (CollectionUtils.isEmpty(roleIds) || CollectionUtils.isEmpty(roleList)) {
            return "";
        }

        StringBuilder s = new StringBuilder();
        for (Long roleId : roleIds) {
            // Role role = roleService.findOne(roleId);
            roleList.forEach(role -> {
                if (role.getId() == roleId) {
                    s.append(role.getDescription());
                    s.append(",");
                }
            });
            /*if (role == null) {
                return "";
            }
            s.append(role.getDescription());
            s.append(",");*/
        }

        if (s.length() > 0) {
            s.deleteCharAt(s.length() - 1);
        }

        return s.toString();
    }

    private String getOrganizationName(Long organizationId) {
        String organizationName = "";
        List<Organization> organizationList = organizationService.findAll();
        if (CollectionUtils.isEmpty(organizationList)) {
            return "";
        }
        for (Organization organization : organizationList) {
            if (organization.getId() == organizationId) {
                organizationName = organization.getName();
            }
        }
        return organizationName;
    }

    @Override
    public int createUser(User user) {
        User u = findByUsername(user.getUsername());
        if (u != null) {
            throw new BizException(ResultCodeEnum.FailedUserAlreadyExist);
        }
        // 加密密码
        passwordHelper.encryptPassword(user);
        /*if (user.getParent()== null){
            user.setParent(false);
        }*/
        return userDao.insert(user);
    }

    @Override
    public int updateUser(User user) {
        return userDao.updateByPrimaryKeySelective(user);
    }

    @Override
    public void deleteUser(Long userId) {
        userDao.deleteByPrimaryKey(userId);
    }

    @Override
    public void changePassword(User user) {
        //User user = userDao.selectByPrimaryKey(userId);
        user.setPassword(user.getPassword());
        passwordHelper.encryptPassword(user);
        userDao.updatePass(user);
    }

    @Override
    public User findOne(Long userId) {
        return userDao.selectByPrimaryKey(userId);
    }

    @Override
    public List<User> findAll() {
        return userDao.selectByExample(new UserExample());
    }

    @Override
    public User findByUsername(String username) {
        UserExample example = new UserExample();
        example.or().andUsernameEqualTo(username);
        List<User> list = userDao.selectByExample(example);
        return !list.isEmpty() ? list.get(0) : null;
    }

    @Override
    public Set<String> findRoles(String username) {
        User user = findByUsername(username);
        if (user == null) {
            return Collections.EMPTY_SET;
        }
        return roleService.findRoles(user.getRoleIdList().toArray(new Long[0]));
    }

    @Override
    public Set<String> findPermissions(String username) {
        User user = findByUsername(username);
        if (user == null) {
            return Collections.EMPTY_SET;
        }
        return roleService.findPermissions(user.getRoleIdList().toArray(new Long[0]));
    }

    @Override
    public List<User> selectAllUserBypId(Integer pId) {
        return userDao.selectAllUserBypId(pId);
    }

    @Override
    public PageResultSet<UserDto> findByUserType(Page page) {
        UserExample example = new UserExample();
        example.setOffset(page.getOffset());
        example.setLimit(page.getLimit());
        example.setOrderByClause("create_date");
        if (!StringUtils.isEmpty(page.getSearch())) {
            example.or().andUsernameLike("%" + page.getSearch() + "%");
        }
        long count = userDao.countByExample(example);
        List<UserDto> dtoList = new ArrayList<>();
        PageResultSet<UserDto> resultSet = new PageResultSet<>();
        //List<Role> roleList = roleService.findAll();

        List<User> userList = userDao.selectByUserType(example);
        List<User> userAllList = userDao.selectByUserType(null);
       // List<Organization> organizationList = organizationService.findAll();
        for (User user : userList) {
            UserDto dto = new UserDto(user);
            dto.setOrganizationName(user.getOrganizationName());
            if (user.getpId() == null) {
                dto.setpName(null);
                dtoList.add(dto);
                continue;
            }
            for (User buser : userAllList) {
                if (user.getpId() == buser.getId()) {
                    dto.setpName(buser.getReallyName());
                    break;
                }
            }
            dtoList.add(dto);
        }
        resultSet.setRows(dtoList);
        resultSet.setTotal(count);
        return resultSet;
    }

    public String queryRiskPhoneByRole(){
        return userDao.queryRiskPhoneByRole();
    }

    public String queryPhoneById(int id){
        return userDao.queryPhoneById(id);
    }

    public String queryParentPhoneById(int id){
        return userDao.queryParentPhoneById(id);
    }

}
